#ifndef MQTT_CLIENT_HPP
#define MQTT_CLIENT_HPP

#include <iostream>
#include <string>
#include <vector>
#include <thread>
#include <mqtt/client.h>


// --- 回调处理类 ---
// 实现 Paho MQTT 的回调接口
class callback : public virtual mqtt::callback,
                 public virtual mqtt::iaction_listener {
    // 连接成功时的回调 (来自 iaction_listener)
    void on_success(const mqtt::token& tok) override {
        std::cout << "--> Connection success" << std::endl;
        is_running = true;
        // 连接成功后，订阅主题
        std::cout << "--> Subscribing to topic '" << topic_ << "' for client "
                  << client_.get_client_id() << " using QoS" << qos_ << std::endl;
        client_.subscribe(topic_, qos_);
    }

    // 连接失败时的回调 (来自 iaction_listener)
    void on_failure(const mqtt::token& tok) override {
        std::cout << "--> Connection failed: " << tok.get_reason_code()
                  << ": " << tok.get_error_message() << std::endl;
        is_running = false;
    }

    // 连接丢失时的回调 (来自 callback)
    void connection_lost(const std::string& cause) override {
        std::cout << "\n--> Connection lost";
        if (!cause.empty())
            std::cout << ": " << cause << std::endl;
        is_running = false;
        // 尝试重新连接
        std::cout << "--> Attempting to reconnect..." << std::endl;
        client_.reconnect()->wait();
    }

    // 消息到达时的回调 (来自 callback)
    void message_arrived(mqtt::const_message_ptr msg) override {
        std::cout << "==> Message arrived" << std::endl;
        std::cout << "  topic: '" << msg->get_topic() << "'" << std::endl;
        // 将 payload 转换为字符串
        std::cout << "  payload: '" << msg->to_string() << "'\n" << std::endl;

        {
            std::unique_lock<std::mutex> lock(queue_mutex);
            msg_queue.push({msg->get_topic(), msg->to_string()});
            queue_cv.notify_one(); // 通知等待的线程
        }
    }

    void delivery_complete(mqtt::delivery_token_ptr token) override {}

public:
    explicit callback(mqtt::async_client& client, mqtt::connect_options& connOpts, const std::string& topic, const int qos)
        : client_(client), connOpts_(connOpts), topic_(topic), qos_(qos) {}

    bool Is_Running() const {
        return is_running.load();
    }

    std::queue<std::pair<std::string, std::string>> msg_queue;  // 消息队列
    std::mutex queue_mutex;                                     // 互斥锁
    std::condition_variable queue_cv;                           // 条件变量
private:
std::atomic<bool> is_running;                               // 运行标志
mqtt::async_client& client_; 
mqtt::connect_options& connOpts_; // 连接选项，可能用于重连
const std::string &topic_;
const int qos_;

};

#endif // __MQTT_CLIENT_HPP